<template>
  <div class="foods-mobile-page">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <n-button quaternary circle @click="$router.back()">
        <n-icon :size="20">
          <ArrowBack />
        </n-icon>
      </n-button>
      <h2>食物管理</h2>
      <n-button type="primary" @click="showCreateModal = true" circle>
        <n-icon :size="18">
          <Add />
        </n-icon>
      </n-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-header">
      <n-input
        v-model:value="searchKeyword"
        placeholder="搜索食物..."
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <n-icon :size="16">
            <Search />
          </n-icon>
        </template>
      </n-input>
    </div>

    <!-- 筛选器 -->
    <div class="filters">
      <n-space>
        <n-select
          v-model:value="filterType"
          placeholder="类型"
          clearable
          :options="filterTypeOptions"
          size="small"
          style="width: 100px"
          @update:value="handleFilter"
        />
        <n-select
          v-model:value="richInNutrients"
          placeholder="富含营养素"
          multiple
          clearable
          :options="nutrientFilterOptions"
          size="small"
          style="width: 150px"
          @update:value="handleFilter"
        />
      </n-space>
    </div>

    <!-- 食物列表 -->
    <div class="foods-list">
      <n-spin :show="foodsStore.loading">
        <!-- 系统预设食物 -->
        <div v-if="displaySystemFoods.length > 0" class="food-section">
          <div class="section-header">
            <n-icon :size="16">
              <Library />
            </n-icon>
            <span>系统预设 ({{ displaySystemFoods.length }})</span>
          </div>

          <div class="food-cards">
            <FoodCardMobile
              v-for="food in displaySystemFoods"
              :key="food.id"
              :food="food as Food"
              @view="viewFood"
              @edit="editFood"
              @delete="deleteFood"
            />
          </div>
        </div>

        <!-- 用户自定义食物 -->
        <div v-if="displayUserFoods.length > 0" class="food-section">
          <div class="section-header">
            <n-icon :size="16">
              <Person />
            </n-icon>
            <span>我的食物 ({{ displayUserFoods.length }})</span>
          </div>

          <div class="food-cards">
            <FoodCardMobile
              v-for="food in displayUserFoods"
              :key="food.id"
              :food="food as Food"
              @view="viewFood"
              @edit="editFood"
              @delete="deleteFood"
            />
          </div>
        </div>

        <!-- 空状态 -->
        <n-empty v-if="displaySystemFoods.length === 0 && displayUserFoods.length === 0" description="没有找到匹配的食物">
          <template #extra>
            <n-button size="small" @click="showCreateModal = true">
              添加食物
            </n-button>
          </template>
        </n-empty>
      </n-spin>
    </div>

    <!-- 创建/编辑食物模态框 -->
    <n-modal
      v-model:show="showCreateModal"
      :mask-closable="true"
      preset="card"
      :title="editingFood ? '编辑食物' : '添加食物'"
      style="width: 100vw; max-width: none; margin: 0; border-radius: 0;"
      :segmented="{ content: true }"
      @after-leave="handleCancelFood"
      @esc="handleCancelFood"
    >
      <FoodFormMobile
        :food="editingFood"
        :nutrients="nutrients"
        :show-cancel-button="true"
        @submit="handleSubmitFood"
        @cancel="handleCancelFood"
      />
    </n-modal>

    <!-- 食物详情模态框 -->
    <n-modal
      v-model:show="showDetailModal"
      :mask-closable="true"
      preset="card"
      title="食物详情"
      style="width: 100vw; max-width: none; margin: 0; border-radius: 0;"
      :segmented="{ content: true }"
      @after-leave="() => showDetailModal = false"
      @esc="() => showDetailModal = false"
    >
      <FoodDetail v-if="viewingFood" :food="viewingFood" :show-close-button="false" />
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useFoodsStore } from '@/stores/foods'
import { Search, Add, Library, Person, ArrowBack } from '@vicons/ionicons5'
import FoodFormMobile from '@/components/foods/FoodFormMobile.vue'
import FoodDetail from '@/components/foods/FoodDetail.vue'
import FoodCardMobile from '@/components/foods/FoodCardMobile.vue'
import type { Food } from '@/types'

const foodsStore = useFoodsStore()

// 响应式数据
const searchKeyword = ref('')
const filterType = ref<string | null>(null)
const richInNutrients = ref<string[]>([])
const showCreateModal = ref(false)
const showDetailModal = ref(false)
const editingFood = ref<Food | null>(null)
const viewingFood = ref<Food | null>(null)

// 计算属性
const filteredFoods = computed(() => foodsStore.filteredFoods)
const nutrients = computed(() => foodsStore.nutrients)

// 根据筛选条件显示的食物列表
const displaySystemFoods = computed(() => {
  if (filterType.value === 'user') return []
  return filteredFoods.value.filter(food => food.is_system)
})

const displayUserFoods = computed(() => {
  if (filterType.value === 'system') return []
  return filteredFoods.value.filter(food => !food.is_system)
})

const filterTypeOptions = [
  { label: '系统预设', value: 'system' },
  { label: '用户自定义', value: 'user' }
]

const nutrientFilterOptions = [
  { label: '蛋白质', value: 'protein' },
  { label: 'Omega-3', value: 'omega3' },
  { label: '膳食纤维', value: 'fiber' },
  { label: '维生素C', value: 'vitamin_c' },
  { label: '钙', value: 'calcium' },
  { label: '铁', value: 'iron' }
]

// 方法
const handleSearch = () => {
  updateSearchParams()
}

const handleFilter = () => {
  updateSearchParams()
}

const updateSearchParams = () => {
  foodsStore.searchParams.keyword = searchKeyword.value || undefined
  foodsStore.searchParams.user_only = filterType.value === 'user' || undefined
  foodsStore.searchParams.system_only = filterType.value === 'system' || undefined
  foodsStore.searchParams.rich_in = richInNutrients.value.length > 0 ? richInNutrients.value : undefined
}

// 监听筛选条件变化
watch([searchKeyword, filterType, richInNutrients], () => {
  updateSearchParams()
}, { deep: true })

const viewFood = (food: Food) => {
  viewingFood.value = food
  showDetailModal.value = true
}

const editFood = (food: Food) => {
  editingFood.value = food
  showCreateModal.value = true
}

const deleteFood = (food: Food) => {
  window.$dialog?.warning({
    title: '确认删除',
    content: `确定要删除食物"${food.name_zh}"吗？`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      // TODO: 实现删除逻辑
      window.$message?.success('删除成功')
    }
  })
}

const handleSubmitFood = async (formData: any) => {
  try {
    if (editingFood.value) {
      // TODO: 实现编辑逻辑
      window.$message?.success('编辑成功')
    } else {
      const result = await foodsStore.createFood(formData)
      if (!result) {
        return // 如果创建失败，不关闭模态框
      }
    }
    
    showCreateModal.value = false
    editingFood.value = null
  } catch (error) {
    console.error('Submit food error:', error)
    window.$message?.error('操作失败，请重试')
  }
}

const handleCancelFood = () => {
  showCreateModal.value = false
  editingFood.value = null
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    foodsStore.fetchFoods(),
    foodsStore.fetchNutrients()
  ])
})
</script>

<style scoped>
.foods-mobile-page {
  background: #f5f5f5;
  padding-bottom: 80px; /* 为底部导航留空间 */
}

.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.nav-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.search-header {
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.filters {
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.foods-list {
  padding: 16px;
}

.food-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #333;
}

.food-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
</style>
